$(document).ready(function() {
	$('#translation').tableEdit();
});

(function( $ ){

	var methods = {
		init : function(options) {
			this.find('.accordion-body').each(function(i, a) {
				a = $(a);
				a.find('table tr').each(function(i, tr) {
					tr = $(tr);
					if (tr.attr('key')) {
						tr.children('td.editable').each(function(i, td) {
							$(this).tableEdit('initCell', {
								block : a.attr('block'),
								key : tr.attr('key')
							});
						});
					}
				});
			});
		},
		initCell : function(data) {
			data.value = this.text();
			data.lang = this.attr('lang');
			this.data('data', data);
			this.mouseover(function (e) {
				$(e.target).addClass('active');
			}).mouseout(function (e) {
				$(e.target).removeClass('active');
			}).bind('click', $.proxy(methods.onClick, this));
		},
		onClick : function(options) {
			this.unbind('click');
			var data = this.data('data');
			console.log('onClick', data);
			this.empty();
			$('<textarea>').val(data.value).appendTo(this)
			.focus()
			.blur($.proxy(methods.onEditDone, this))
			.keyup($.proxy(function(e) {
				if (e.keyCode == 27) {
					this.tableEdit('onEditCancel', e);
				}
			}, this));
		},
		onEditDone : function(e) {
			var data = this.data('data'),
			el = $(e.target);
			data.value = el.val();
			this.data('data', data).text(data.value);
			this.bind('click', $.proxy(methods.onClick, this));
			$.ajax({
				  type: 'POST',
				  url: 'translation/save',
				  data: data,
				  success: $.proxy(methods.onSaved, this),
				  dataType: 'json'
				});
		},
		onEditCancel : function(e) {
			var data = this.data('data');
			this.text(data.value)
			
			this.bind('click', $.proxy(methods.onClick, this));
		},
		onSaved : function(e) {
			console.log(this, arguments);
		}
	};

  $.fn.tableEdit = function(method) {
		if (methods[method]) {
			return methods[method].apply(this, Array.prototype.slice.call(
					arguments, 1));
		} else if (typeof method === 'object' || !method) {
			return methods.init.apply(this, arguments);
		} else {
			$.error('Method ' + method + ' does not exist on jQuery.tableEdit');
		}

	};

	})( jQuery );